<template>
  <view class="chatbox" ref="emoji">
    <view class="chatbox-main">
      <view class="bt-img" @click="changeRecord">
        <image src="@/static/images/chartroom/yy.png" mode=""></image>
      </view>
      <view :class="{ displaynode: info.isRecord }">
        <textarea v-model="info.message" auto-height @focus="textFocus"></textarea>
      </view>
      <view class="record btn" :class="{ displaynode: !info.isRecord }" @touchstart="touchstart" @touchend="touchend"
        @touchmove="touchmove">
        按住说话</view>
      <view class="right">
        <view class="bt-img e">
          <image @click="changeEmoji" src="@/static/images/chartroom/bq.png" mode=""></image>
        </view>
        <view class="bt-img e" :class="{ button: info.message != '' }">
          <image src="@/static/images/chartroom/tj.png" mode="" v-show="info.message == ''" @click="showMore"></image>
          <view class="but" @click="sendMsg" v-show="info.message != ''">发送</view>
        </view>
      </view>
    </view>
    <view class="emoji" :class="{ displaynode: !info.isEmojs }">
      <view class="emoji-delete">
        <image src="@/static/images/chartroom/back.png" @click="delMsg" mode=""></image>
      </view>
      <Emoji @emotion="emotion"></Emoji>
    </view>
    <view class="more" :class="{ displaynode: !info.isMore}">
      <view class="more-list">
        <view class="more-list-item" @click="sendImg('album')">
          <image src="@/static/images/chartroom/tp.png" mode=""></image>
          <view class="more-list-item-title"><span>图片</span></view>
        </view>
        <view class="more-list-item" @click="sendImg('camera ')">
          <image src="@/static/images/chartroom/pz.png" mode="">
          </image>
          <view class="more-list-item-title"><span>拍摄</span></view>
        </view>
        <view class="more-list-item" @click="chooseLocation">
          <image src="@/static/images/chartroom/dw.png" mode=""></image>
          <view class="more-list-item-title"><span>位置</span></view>
        </view>
        <view class="more-list-item">
          <image src="@/static/images/chartroom/sp.png" mode=""></image>
          <view class="more-list-item-title"><span>视频</span></view>
        </view>
        <view class="more-list-item">
          <image src="@/static/images/chartroom/wj.png" mode=""></image>
          <view class="more-list-item-title"><span>文件</span></view>
        </view>
      </view>
    </view>
  </view>
  <!-- 点击录音出现的遮罩层 -->
  <view class="voice-bg" :class="{ displaynode: !info.voiceBg }">
    <view class="voice-bg-len">
      <view class="voice-bg-time" :style="{width:(info.vlength/0.6) + '%'}">{{info.vlength}}″</view>
    </view>
    <view class="voice-del" :class="{delbg:info.isShow}">上滑取消录音</view>
  </view>
</template>

<script setup>
  // h5不兼容这个方法
  const recorderManager = uni.getRecorderManager();
  import {
    reactive,
    ref,
    nextTick
  } from 'vue'
  import mitter from '@/utils/mitt';
  import Emoji from '@/components/emoji/emoji.vue';
  const info = reactive({
    message: '', //输入的消息
    isRecord: false, //音频切换
    isEmojs: false, //表情显示
    isMore: false, //更多显示
    voiceBg: false, //录音时显示
    flag: 1, //更多和表情切换时，阻止动画 只在第一次点击的时候添加动画
    height: 0,
    timer: null, //定时器
    vlength: 0, //音频时长
    pageY: 0, //按住说话时初始位置
    isShow: false, //动态控制上滑的样式
    isShowAnE: false,
    isShowAnM: false,
  })
  const emoji = ref(null)
  //显示更多
  function showMore() {
    info.isRecord = false
    info.isMore = !info.isMore
    if (info.isEmojs) info.isEmojs = !info.isEmojs
    nextTick(() => { //在改变数据|状态之后，将下面的回调延迟到下次dom更新之后执行。
      //dom更新了
      getHeight()
    })
  }
  //点击弹出表情 
  function changeEmoji() {
    info.isRecord = false
    info.isEmojs = !info.isEmojs
    if (info.isMore) info.isMore = !info.isMore
    //dom未更新
    //若不使用nextTick，因为dom还没有重新渲染，所以height获取高度为0
    //await nextTick()
    nextTick(() => { //在改变数据|状态之后，将下面的回调延迟到下次dom更新之后执行。
      //dom更新了
      getHeight()
    })
  }

  //获取弹出层高度
  function getHeight() {
    const query = uni.createSelectorQuery().in(this);
    query.select('.chatbox').boundingClientRect(data => {
      // console.log('data', data)  
      info.height = data.height - 50
      // console.log(info.height)
      mitter.emit('dealHeight', data.height - 50)
    }).exec();
  }
  //点击切换语音|输入框
  function changeRecord() {
    info.isRecord = !info.isRecord
    info.isEmojs = false
    info.isMore = false
    info.flag = 1
    nextTick(() => getHeight())
  }
  //发送图片
  function sendImg(way) {
    //console.log(way)
    let count = 9
    if (way == 'album') count = 9
    else count = 1
    uni.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: [way], //从相册选择
      success: function(res) {
        let filePaths = res.tempFilePaths
        for (let i = 0; i < filePaths.length; i++) {
          mitter.emit('getMsg', {
            message: filePaths[i],
            types: 1
          })
        }
      }
    })
  }

  //发送消息
  function sendMsg() {
    if (info.message == '') {
      uni.showToast({
        title: '输入内容不能为空',
        icon: 'error'
      })
      return
    }
    //触发事件
    mitter.emit('getMsg', {
      message: info.message,
      types: 0
    })
    info.message = ''
  }

  //接收表情并处理
  function emotion(emoji) {
    // console.log(emoji);
    info.message += emoji
  }

  //输入框获取焦点时，如果表情弹出，那么表情消失
  function textFocus() {
    if (info.isMore) {
      info.isMore = !info.isMore
      info.flag = 1
      nextTick(() => { //在改变数据|状态之后，将下面的回调延迟到下次dom更新之后执行。
        //dom更新了
        getHeight()
        let ele = document.querySelector('.more')
        if (info.isMore) {
          ele.classList.add('an')
        } else {
          ele.classList.remove('an') //删除动画
        }
      })
    }
    if (info.isEmojs) {
      info.isEmojs = !info.isEmojs
      info.flag = 1
      nextTick(() => { //在改变数据|状态之后，将下面的回调延迟到下次dom更新之后执行。
        //dom更新了
        getHeight()
        let ele = document.querySelector('.emoji')
        if (info.isEmojs) {
          ele.classList.add('an')
        } else {
          ele.classList.remove('an') //删除动画
        }
      })
    }
  }
  //点击x退格
  function delMsg() {
    if (info.message.length > 0) {
      let len = info.message.length
      //#region 
      //判断是否是emoji字符
      // let reg = /\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g
      // let res=  info.message.match(reg)  //返回emoji数组
      //#endregion
      for (let i = len - 1; i >= 0; i--) {
        //转为acsall码
        if (info.message.charCodeAt(i) < 50000) { //比较局限
          //不是表情的普通删法
          info.message = info.message.substring(0, len - 1); //截取调最后一个字符
          break;
        } else {
          info.message = info.message.substring(0, len - 2);
          break
        }
      }
    }
  }

  //开始说话 录音
  function touchstart(e) {
    console.log('开始')
    info.pageY = e.changedTouches[0].pageY
    info.voiceBg = true
    let i = 1;
    info.timer = setInterval(() => {
      info.vlength = i
      i++
      console.log(i)
      if (i > 60) {
        clearInterval(info.timer)
        touchend() //提交音频
      }
    }, 1000)
    recorderManager.start();
  }
  //结束说话
  function touchend() {
    console.log('结束')
    info.voiceBg = false
    clearInterval(info.timer)
    recorderManager.stop();
    recorderManager.onStop(function(res) {
      let data = {
        voice: res.tempFilePath,
        time: info.vlength
      }
      if (info.vlength == 0) {
        uni.showToast({
          title: '说话时间太短了~',
          icon: 'error',
        })
        return;
      }
      if (info.isShow == false) {
        mitter.emit('getMsg', {
          message: data,
          types: 2
        })
      }
      info.vlength = 0
    });
  }
  //上滑终止录音
  function touchmove(e) {
    if (info.pageY - e.changedTouches[0].pageY > 60) {
      info.isShow = true
    } else {
      info.isShow = false
    }
    console.log('删除')
  }

  //定位相关功能
  function chooseLocation() {
    uni.chooseLocation({
      success: function(res) {
        let data = {
          name: res.name,
          address: res.address,
          latitude: res.latitude,
          longitude: res.longitude
        }
        //js对象转为json字符串
        data = JSON.stringify(data)
        mitter.emit('getMsg', {
          message: data,
          types: 3
        })
      }
    });
  }
</script>

<style lang="scss" scoped>
  .chatbox {
    // height: 5.2857rem;
    background: var(--bg-color-grey);
    position: fixed;
    width: 100%;
    bottom: 0;
    z-index: 102;
    border-top: 1px solid rgba(179, 179, 180, 0.247);

    &-main {
      width: 100%;
      padding: 20rpx;
      display: flex;
      align-items: center;

      .bt-img {
        height: 56rpx;
        width: 56rpx;
        margin-left: 10rpx;

        image {
          height: 56rpx;
          width: 56rpx;
        }
      }

      .button {
        width: 84rpx;
        height: 56rpx;
      }

      .e {
        margin-right: 16rpx;

        .but {
          text-align: center;
          background-color: #fff;
          border-radius: 10px;
          padding: 8rpx 10rpx;
          width: 84rpx;
          height: 56rpx;
          border: 1px solid #eee;
          font-size: 25rpx;
        }
      }

      .right {
        display: flex;
        width: 164rpx;
      }
    }

    .emoji {
      position: relative;
      width: 100%;
      height: 360rpx;
      background: rgba(236, 237, 238, 1);
      box-shadow: 0 -4rpx 0 rgba(0, 0, 0, 0.1);

      .emoji-delete {
        position: absolute;
        padding: 16rpx;
        background: #fff;
        opacity: 0.8;
        border-radius: 10px;
        bottom: 20rpx;
        right: 20rpx;

        image {
          height: 42rpx;
          width: 56rpx;
        }
      }
    }

    .more {
      position: relative;
      width: 100%;
      height: 360rpx;
      background: rgba(236, 237, 238, 1);
      box-shadow: 0 -4rpx 0 rgba(0, 0, 0, 0.1);

      &-list {
        display: flex;
        flex-wrap: wrap;
        padding: 8rpx;
        padding-top: 30rpx;
        width: 100%;
        height: 100%;

        &-item {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 25%;

          image {
            background: #fff;
            border-radius: 10px;
            padding: 8rpx;
            height: 88rpx;
            width: 88rpx;
          }

          &-title {
            // line-height: 2.4286rem;
            margin: 20rpx 0;
            font-size: 24rpx;
          }
        }
      }
    }

  }

  .voice-bg {
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    position: fixed;
    top: 0;
    bottom: 0;
    z-index: 101;

    &-len {
      height: 84rpx;
      width: 600rpx;
      position: absolute;
      border-radius: 42rpx;
      top: 50%;
      left: 50%;
      transform: translate(-50%);
      text-align: center;
      line-height: 84rpx;
      font-size: 36rpx;
      background-color: rgba(255, 255, 255, .3);

      .voice-bg-time {
        display: inline-block;
        min-width: 120rpx;
        background-color: #89d961;
        border-radius: 42rpx;
      }
    }

    .voice-del {
      position: absolute;
      bottom: 120rpx;
      margin-bottom: 60rpx;
      left: 50%;
      transform: translate(-50%);
      color: #fff;
      width: 50%;
      font-size: 34rpx;
      text-align: center;
      padding: 20rpx;
      border-radius: 42rpx;
      background-color: rgba(255, 255, 255, .3);
    }
  }

  uni-textarea {
    // width: 60%;
    margin: 0 30rpx;
    padding: 13.5rpx;
    background-color: #fff;
    width: 420rpx;
    border-radius: 16rpx;
    height: 68rpx;
  }

  .an {
    animation-name: srcollan;
    animation-duration: .5s;
  }


  .btn {
    // flex: 1;
    border-radius: 16rpx;
    padding: 15rpx;
    background-color: #fff;
    margin: 0 30rpx;
  }

  .record {
    text-align: center;
    font-size: 30rpx;
    height: 67rpx;
    color: var(--text-color-placeholder);
    // width: 58%;
    width: 420rpx;
  }

  .displaynode {
    display: none;
  }

  .delbg {
    background-color: #fff !important;
    color: black !important;
  }

  // 定义动画
  @keyframes srcollan {
    0% {
      width: 100%;
      height: 0px;
    }

    100% {
      width: 100%;
      height: 180px;
    }
  }

  @keyframes srcollun {
    0% {
      width: 100%;
      height: 180px;
    }

    100% {
      width: 100%;
      height: 0px;
    }
  }
</style>
